import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import moment from 'moment';
// import { routerRedux, Route, Switch } from 'dva/router';
import { Form, Input, Select, Button, Badge } from 'antd';
import StandardTable from '@/components/StandardTable';
import SelectForm from '@/components/SelectForm';
import ManageList from '@/components/ManageList';
import TableButtons from '@/components/TableButtons';
import AdSelect from '@/components/AdSelect';
import { codes, STATUS, EventType, NoticeMode, statusMap } from './utils';
import { formateDateToMin } from '@/utils/common';

const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;

@ManageList
@connect(({ content, common, loading }) => ({
  content,
  loading: loading.effects['content/msgContentList'],
  dictObject: common.dictObject,
}))
@Form.create()
export default class ContentList extends Component {
  state = {
    expandForm: false,
    selectedRows: [],
    visible: false,
    checkIds: [],
    formValues: {},
  };
  className = 'contentList';

  columns = [
    {
      title: '事件代码',
      dataIndex: 'eventCode',
      render: text => <span title={text}>{text}</span>,
      width: 200,
    },
    {
      title: '事件名称',
      dataIndex: 'eventName',
      render: text => <span title={text}>{text}</span>,
      width: 200,
    },
    {
      title: '消息内容',
      dataIndex: 'content',
      render: text => <span title={text}>{text}</span>,
      width: 250,
    },
    {
      title: '状态',
      dataIndex: 'state',
      render(text) {
        const val = <AdSelect data={STATUS} value={text} onlyRead={true} />;
        return <Badge status={statusMap[text]} text={val} />;
      },
      width: 100,
    },
    {
      title: '通知方式',
      dataIndex: 'noticeMode',
      render: text => <AdSelect data={NoticeMode} value={text} onlyRead={true} />,
    },
    {
      title: '消息产生方',
      dataIndex: 'messageGenerator',
      render: text => <span title={text}>{text}</span>,
    },
    {
      title: '消息发送账号',
      dataIndex: 'sendAccount',
      render: text => <span title={text}>{text}</span>,
    },
    {
      title: '消息接收账号',
      dataIndex: 'receiverAccount',
      render: text => <span title={text}>{text}</span>,
    },
    {
      title: '消息发送时间',
      dataIndex: 'sendTime',
      render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
    },
  ];
  componentDidMount() {
    this.getContentList();
  }

  getContentList = (params = {}) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'content/msgContentList',
      payload: params,
    });
  };

  //重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    this.getContentList();
  };

  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  handleSelectRows = rows => {
    // console.log('选择', rows);
    let ids = [];
    if (Array.isArray(rows) && rows.length > 0) {
      rows.map((item, i) => {
        ids.push(item.id);
      });
    }
    this.setState({
      selectedRows: rows,
      checkIds: ids,
    });
  };

  //查询
  handleSearch = values => {
    // if (!values) {
    //   return;
    // }
    const { ...value } = values;
    this.setState({
      formValues: value,
    });
    this.getContentList(value);
  };
  // 分页操作：改参数
  handleStandardTableChange = param => {
    const { formValues } = this.state;
    const params = {
      ...formValues,
      ...param,
    };
    this.getContentList(params);
  };

  //重试：
  retry = () => {
    const { dispatch } = this.props;
    const { checkIds, formValues } = this.state;
    let params = {};
    params.ids = checkIds;
    dispatch({
      type: 'content/retryMsgSend',
      payload: params,
      callback: res => {
        console.log('res', res);
        this.getContentList(formValues);
      },
    });
  };
  render() {
    const {
      loading,
      content: { msgContentList },
      form,
      isMobile,
      dictObject,
    } = this.props;
    const { getFieldDecorator } = form;
    const { selectedRows, expandForm } = this.state;
    const firstFormItem = (
      <FormItem label="事件代码">
        {getFieldDecorator('eventCode')(<Input placeholder="请输入" />)}
      </FormItem>
    );
    const secondFormItem = (
      <FormItem label="状态">
        {getFieldDecorator('state')(
          <Select placeholder="请选择" style={{ width: '100%' }} allowClear={true}>
            <Option value="">请选择</Option>
            {STATUS.map(v => {
              return <Option value={v.code}>{v.value}</Option>;
            })}
          </Select>
        )}
      </FormItem>
    );

    // secondForm 参数
    const otherFormItem = [
      [
        <FormItem label="事件名称">
          {getFieldDecorator('eventName')(<Input placeholder="请输入" />)}
        </FormItem>,
      ],
      [
        <FormItem label="消息产生方">
          {getFieldDecorator('messageGenerator')(<Input placeholder="请输入" />)}
        </FormItem>,
        <FormItem label="通知方式">
          {getFieldDecorator('noticeMode')(
            <Select placeholder="请选择" style={{ width: '100%' }} allowClear={true}>
              <Option value="">请选择</Option>
              {NoticeMode.map(v => {
                return <Option value={v.code}>{v.value}</Option>;
              })}
            </Select>
          )}
        </FormItem>,
        'operatorButtons',
      ],
    ];
    const selectFormParams = {
      firstFormItem,
      secondFormItem,
      otherFormItem,
      form,
      className: this.className,
      handleFormReset: this.handleFormReset,
      handleSearch: this.handleSearch,
      toggleForm: this.toggleForm,
    };
    const tableButtonsParams = {
      show: true,
      // handleAdd: this.handleAdd,
      buttons: (
        <Button onClick={() => this.retry()} disabled={selectedRows.length > 0 ? false : true}>
          重试
        </Button>
      ),
      selectedRows: selectedRows,
    };

    return (
      <Fragment>
        <SelectForm {...selectFormParams} />
        <TableButtons {...tableButtonsParams} />
        <StandardTable
          selectedRows={selectedRows}
          loading={loading}
          data={msgContentList}
          columns={this.columns}
          onSelectRow={this.handleSelectRows}
          onPaginationChange={this.handleStandardTableChange}
          expandForm={expandForm}
          className={this.className}
          code={codes.page}
          getCheckboxProps={record => {
            return record.state !== 'PUSH-FAIL';
          }}
        />
      </Fragment>
    );
  }
}
